$(function(){
		var canSubmit = false;
		
		$(".container").on("click", function(e){
			var target = $(e.target);
			var targetId = target.attr("id");

			//保存修改地址
			if(targetId == 'btnSave'){
				var _form = target.closest(".form-address");
	        	//验证并提交form 提交后续步骤在ajax success后进行
	        	submitForm(_form,1);
			}
			//关闭修改地址
			else if(targetId == 'btnClose'){
				target.closest(".form-address")[0].reset();
				updateDIV.slideUp("fast");
			}
			//确认收货地址
			else if(targetId == 'btnConfirm'){
				//当前选中
				if(checkedVal != -1){
					var checkedTD = target.closest(".addressList").find(".table-body__cont .input-address[value=" + checkedVal + "]").closest("td");
					var tds = checkedTD.nextAll();
					var receiverName = tds.eq(0).text();
					var allAddr = tds.eq(1).text();
					var receiverPhone = tds.eq(2).text();
					valLiFromForm(receiverName, receiverPhone,allAddr, checkedVal);
					//flag重置
					checkedVal = -1;
	            	updatedIds = '';
					confirmDIVShow();
				}
				else{
					alert("请选择收货地址");
				}
				
			}
			//从确认收货地址返回
			else if(targetId == 'btnReturn'){
				$("#btnClose").click();
				var addressId = $("#addressId").val();
				if(updatedIds.indexOf(addressId) > -1){
					$.ajax({
			            type: "post",
			            url: "getAddrById",
			            dataType:'json',
						data: {
							addressId : addressId
						},
			            success: function(data) {
			            	var addr = data.address[0];
			            	valLiFromForm(addr.receiverName, addr.receiverPhone,addr.province + addr.city + addr.area + addr.address, addr.id);
			            	//flag重置
			            	checkedVal = -1;
			            	updatedIds = '';
			            },
			            error: function(errorMsg) {
			                alert("请求数据失败!");
			            }
			        });
				}
				confirmDIVShow();
			}
			//使用其他地址
			else if(targetId == 'btnOthers'){
				valAddressList();
			}
			//使用新地址
			else if(targetId == 'btnCreate'){
				createDIVShow();
			}
			//新增地址并确认使用
			else if(targetId == 'btnCreateConfirm'){
				var _form = target.closest(".form-address");
	        	//验证并提交form 提交后续步骤在ajax success后进行
	        	submitForm(_form,0);
			}
			//新增地址返回
			else if(targetId == 'btnCreateReturn'){
				var _form = target.closest(".form-address");
	        	//清空form
	        	_form[0].reset();
	        	//隐藏并切换div
	        	confirmDIVShow();
			}
			//返回购物车
			else if(target.hasClass("btn-backCart")){
				checkedVal = -1;
				updatedIds = '';
				location.href = "../orderPc/cart"
			}
			//结算
			else if(targetId == 'settleAccounts'){
				if($("#addressConfirmedDIV").is(":visible")){
					var sellerId = $("#sellerId").val();
					var addressId = $("#addressId").val();
					var memoInput = $("#memo");
					var memo = $("#memo").val();
					var goodsItemIds = $("#goodsItemIds").val();
					var counts = $("#counts").val();
					var orderNo = $("#orderNo").val();
					var cartIds = sessionStorage.getItem("cartIds");
					
					if(!validateMome(memoInput, txtReg)){
						return false;
					}
					
					$.ajax({
			            type: "post",
			            url: "settleAccounts",
			            dataType:'json',
						data: {
							sellerId : sellerId,
							addressId : addressId,
							memo : memo,
							goodsItemIds : goodsItemIds,
							counts : counts,
							cartIds :　cartIds,
							orderNo : orderNo
						},
			            success: function(data) {
			            	if(data.returnFlag == '1'){
			            		if(data.returnCode == 'A001'){
                                    layer.open({
                                        content: data.info,
                                        scrollbar: false
                                    });
			            		}
			            		else if(data.returnCode == 'A002'){
                                    layer.open({
                                        content: '包含下架商品',
                                        scrollbar: false
                                    });
			            		}
			            		else if(data.returnCode == 'A003'){
                                    layer.open({
                                        content: '访问错误',
                                        scrollbar: false
                                    });
			            		}
			            		else if(data.returnCode == 'A004'){
                                    layer.open({
                                        content: '该订单已存在，不要重复提交',
                                        scrollbar: false
                                    });
			            		}
			            		return false;
			            	}
			            	location.href = "../alipay/scPay?orderId=" + data.orderId;
			            },
			            error: function(errorMsg) {
			                alert("请求数据失败!");
			            }
			        });
				}
				else{
                    layer.open({
                        content: '请确认收货地址',
                        scrollbar: false
                    });
					return false;
				}
			}
		});

        //绑定验证
        $(".form-address--center").on("onreadystatechange input blur", function(e){
        	var target = $(e.target);
        	var targetId = target.attr("id");

        	if(targetId=='receiverName'){
        		validateInput(target, hanziReg);
        	}
        	if(targetId=='receiverPhone'){
        		validateInput(target, phoneReg);
        	}
        	if(targetId=='address'){
        		validateInput(target, txtReg);
        	}
        	
        });
        
        $("#memo").on("onreadystatechange input blur", function(e){
        	var target = $(e.target);
        	validateMome(target, txtReg);
        });
        
        $(".form-address--center input.chkDefault").on("change", function(){
        	valIsDefault($(this));
        });
        
});

var createDIV = $("#addressCreateDIV");
var modifyDIV = $("#addressModifyDIV");
var updateDIV = $("#updateAddressDIV");
var confirmDIV = $("#addressConfirmedDIV");
//选中的地址
var checkedVal = -1;
var updatedIds = '';
var defTxt = ' | 默认地址';

/*-------验证 START------*/
var hanziReg= /^(([\u4e00-\u9fa5]{2,8})|([a-zA-Z]{2,16}))$/;
var phoneReg= /^[1][0-9]{10}$/;
//-----/^\S+$/
var txtReg = /^[\u4e00-\u9fa5\da-zA-Z\-\_]+$/; 


function submitForm(_form, type){ //0是新增 1是修改
	var id = _form.find("#id").val();
	var receiverName = _form.find("#receiverName");
	var receiverPhone = _form.find("#receiverPhone");
	var province = _form.find("#province").val();
	var city = _form.find("#city").val();
	var area = _form.find("#area").val();
	var address = _form.find("#address");
	var isDefault = _form.find("#isDefault").val();
	
	var canSubmit = validateInput(receiverName, hanziReg)&&
					validateInput(receiverPhone, phoneReg)&&
					validateInput(address, txtReg);
	
	if(canSubmit){
		if(type == 0){//新建地址
			$.ajax({
	            type: "post",
	            url: "newAddr",
	            dataType:'json',
				data: _form.serialize(),
	            success: function(data) {
	            	var allAddr = province + city + area + address.val();
	            	//赋值到地址确认
	            	valLiFromForm(receiverName.val(),receiverPhone.val(),allAddr,data.addressId);
	            	//清空新增地址form
	            	_form[0].reset();
	            	//重设默认按钮
	            	resetDefChk(_form.find("input.chkDefault"));
	            	//新增地址的返回按钮显示
	            	btnCreateReturnShow();
	            	//隐藏并切换div
	            	confirmDIVShow();
	            },
	            error: function(errorMsg) {
	                alert("请求数据失败!");
	            }
	        });
		}
		else if(type == 1){//更新地址
			$.ajax({
	            type: "post",
	            url: "modifyAddr",
	            dataType:'json',
				data: _form.serialize(),
	            success: function(data) {
	            	//更新选择地址列表
	            	updateAddressTable(id,receiverName.val(),receiverPhone.val(),province,city,area,address.val(),isDefault);
	            	//重置更新form
	            	_form[0].reset();
	            	//收起更新form
	            	updateDIV.slideUp("fast");
	            },
	            error: function(errorMsg) {
	                alert("请求数据失败!");
	            }
	        });
		}
	}
	
	return canSubmit;
}

function validateInput(inputDom, validateReg){
	var inputVal = inputDom.val();
	var msgDom = inputDom.closest(".form-group").find(".js-line-alert");
	var returnFlag = false;

	if(inputVal.length === 0){
		showWarning(inputDom, msgDom);
	}
	else if(!validateReg.test(inputVal)){
		showWarning(inputDom, msgDom);
	}
	else{
		hideWarning(inputDom, msgDom);
		returnFlag = true;
	}
	return returnFlag;
}

function validateMome(inputDom, validateReg){
	var inputVal = inputDom.val();
	var msgDom = inputDom.closest(".form-group").find(".js-line-alert");
	var returnFlag = false;

	//inputVal.length > 0 && !validateReg.test(inputVal)
	if(inputVal.length > 255 ){
		showWarning(inputDom, msgDom);
	}
	else{
		hideWarning(inputDom, msgDom);
		returnFlag = true;
	}
	return returnFlag;
}

function showWarning(inputDom, msgDom){
	msgDom.show();
	inputDom.addClass("input-error border-error");
}

function hideWarning(inputDom, msgDom){
	msgDom.hide();
	inputDom.removeClass("input-error border-error");
}
/*-------验证 END------*/

/*-------操作后变换dom、赋值  START------*/
function valAddressList(){
	var table = $(".addressList .table-body__cont");
	
	table.empty();
	$.ajax({
        type: "post",
        url: "addrLst",
        dataType:'json',
        success: function(data) {
        	//地址列表赋值
        	if(data.addressList){
        		$.each(data.addressList, function(index,value){
        			var spanTxt = '';
        			if(value.isDefault == 1){
        				spanTxt = defTxt;
        			}
        			var allAddr=value.province + value.city + value.area + value.address;
        			var newRow = '<tr><td><input type="checkbox" class="input-address" value="'+value.id+'"></td><td><p>'+value.receiverName+'</p></td><td data-province=' + value.province + ' data-city='+ value.city + ' data-area=' + value.area + ' data-address=' + value.address + '><p>'+allAddr+'</p></td><td><p>'+value.receiverPhone+'</p></td><td><p class="address-operate"><a class="addressUpdate" href="javascript:">修改</a><span data-isDefault="'+value.isDefault+'">'+spanTxt+'</span></p></td></tr>';
        			table.append(newRow);
        		});
        		
        		bindChooseAddr(table);
        		
        		checkedVal = $("#addressId").val();
        		table.find(".input-address[value="+ checkedVal +"]").click();
        	}
        	//地址列表显示
        	modifyDIVShow();
        },
        error: function(errorMsg) {
            alert("请求数据失败!");
        }
    });
}

function valLiFromForm(receiverName, receiverPhone, allAddr, addressId){
	//赋值addressId隐藏域
	$("#addressId").val(addressId);
	var list = $(".receiverList li");
	list[0].getElementsByClassName("receiverInfo")[0].innerHTML = receiverName;
	list[1].getElementsByClassName("receiverInfo")[0].innerHTML = allAddr;
	list[2].getElementsByClassName("receiverInfo")[0].innerHTML = receiverPhone;
}

function updateAddressTable(id,receiverName,receiverPhone,province, city, area, address,isDefault){
	updatedIds += id + ",";
	
	var table = $(".addressList .table-body__cont");
	var updatedTR = table.find(".input-address[value=" + id + "]").closest("tr");
	var tds = updatedTR.find("td");
	
	chkAddr(table, tds.eq(0).children(".input-address"));
	tds.eq(1).children("p").text(receiverName);
	var allAddr = tds.eq(2);
	allAddr.attr("data-province", province);
	allAddr.attr("data-city", city);
	allAddr.attr("data-area", area);
	allAddr.attr("data-address", address);
	allAddr.children("p").text(province + city + area + address)
	tds.eq(3).children("p").text(receiverPhone);
	
	var isDefSpan = tds.eq(4).find("span");
	
	var orgDefRow = table.children('tr:eq(0)');
	
	if(isDefault==1){
		//去掉原来的“默认地址”
		orgDefRow.find("span").attr("data-isDefault", 0).text('');
		//添加现在的“默认地址”
		isDefSpan.text(defTxt);
		//更改为默认地址后置顶
		orgDefRow.before(updatedTR);
	}
	else{
		isDefSpan.text('');
	}
	
	isDefSpan.attr("data-isDefault", isDefault);
	
}
/*-------操作后变换dom、赋值  END------*/

/*-------绑定事件 START------*/
//修改地址
function bindChooseAddr(table){
	table.off("click");
	table.on("click", function(e){
		var target = $(e.target);
		
		if(target.hasClass("input-address")){
			if(target.prop("checked")){
				var allChks = table.find(".input-address");
				checkedVal = target.val();
				allChks.each(function(){
					if(this.value!=checkedVal){
						this.checked = false;
					}
				});
			}
			else{
				checkedVal = -1;
			}
		}
		
		if(target.hasClass("addressUpdate")){
		    var tds = target.closest("tr").find("td");
		    var id = tds.eq(0).children(".input-address").val();
			var receiverName = tds.eq(1).text();
			var allAddr = tds.eq(2);
			var province = allAddr.attr("data-province");
			var city = allAddr.attr("data-city");
			var area = allAddr.attr("data-area");
			var address = allAddr.attr("data-address");
			var receiverPhone = tds.eq(3).text();
			var isDefault = tds.eq(4).find("span").attr("data-isDefault");
			
		    var _form = $("#updateAddressDIV .form-address");
		    _form.find("#id").val(id);
			_form.find("#receiverName").val(receiverName);
			_form.find("#receiverPhone").val(receiverPhone);
			_form.find("#province").val(province);
			_form.find("#city").val(city);
			_form.find("#area").val(area);
			_form.find("#address").val(address);
			_form.find("#isDefault").val(isDefault);
			var chk = _form.find("#chkDefaultUpdate");
			changeDefChk(isDefault ,chk);
			
		    updateDIV.slideDown("fast");
		}
	});
}

function chkAddr(table, checked){
	checked.prop("checked", true);
	var allChks = table.find(".input-address");
	checkedVal = checked.val();
	allChks.each(function(){
		if(this.value!=checkedVal){
			this.checked = false;
		}
	});
}

/*-------绑定 END------*/
function resetDefChk(chk){
	chk.prop("checked", false);
	valIsDefault(chk);
}

function valIsDefault(chk){
	var chkChecked = chk.prop("checked");
	isDef = chk.prev();
	if(chkChecked){
		isDef.val(1);
	}
	else{
		isDef.val(0);
	}
}

function changeDefChk(isDefault ,chk){
	if(isDefault == 0){
		chk.prop("checked", false);
	}
	else if(isDefault == 1){
		chk.prop("checked", true);
	}
}

function btnCreateReturnShow(){
	$("#btnCreateReturn").show();
	$("#btnCreateConfirm").removeClass("col-sm-9 col-sm-offset-3").addClass("col-sm-6 col-sm-offset-1");
}

function modifyDIVShow(){
	createDIV.hide();
    modifyDIV.show();
    confirmDIV.hide();
}

function createDIVShow(){
	createDIV.show();
    modifyDIV.hide();
    confirmDIV.hide();
}

function confirmDIVShow(){
	createDIV.hide();
    modifyDIV.hide();
    confirmDIV.show();
}
